import time
import os
import requests
from func_timeout import func_set_timeout
import json
import subprocess
import uiautomator2 as u2
import cv2
import random
import yoloimg

class fun:
    device=None
    si=None
    schange=None

    def __init__(self,device,i,change):
        self.device=device
        self.si=i
        self.schange=change

    def get_public_ip(self,d):
        try:
            response = requests.get('https://api.ipify.org?format=json')
            if response.status_code == 200:
                return response.json()['ip']
            else:
                print("Failed to retrieve IP address:", response.status_code)
                return None
        except Exception as e:
            print("Error occurred:", e)
            return None

    def check_proxy(self,proxy, username, password):
        try:
            proxies = {
                "http": f"http://{username}:{password}@{proxy}",
                "https": f"http://{username}:{password}@{proxy}"
            }
            response = requests.get("http://baidu.com", proxies=proxies, timeout=5)
            if response.status_code == 200:
                return True
        except Exception as e:
            print(f"Proxy {proxy} is not working: {e}")
        return False

    def check_proxy2(self,proxy):
        try:
            response = requests.get("http://baidu.com", proxies={"http": proxy, "https": proxy}, timeout=5)
            if response.status_code == 200:
                return True
        except Exception as e:
            print(f"Proxy {proxy} is not working: {e}")
        return False

    def isexists(self,d,arr,n=5):
        i=0
        b=True
        while(b):
            for name in arr:
                if(d(resourceId=name).exists):
                    b=False
                    return d(resourceId=name)
                time.sleep(0.2)
            i+=1
            if(i>n):
                return None

    def flight(self,d):
        device=self.device
        subprocess.Popen("adb -s "+device+ " shell am start -a android.settings.WIRELESS_SETTINGS").stdout

        scroll_headers=self.isexists(d,['com.android.settings:id/scroll_headers','com.android.settings:id/recycler_view'],2)

        if(scroll_headers):
            # 找到指定类型的子元素列表
            child_elements = scroll_headers.child(className="android.widget.LinearLayout")
            i=0;
            for first_linear_layout in child_elements:
                #print('first_linear_layout==',first_linear_layout)
                if(i==13):
                    first_linear_layout.click()
                i+=1

            recycler_view=self.isexists(d,['com.android.settings:id/recycler_view'],2)
            if(recycler_view):
                # 找到指定类型的子元素列表
                child_elements = recycler_view.child(className="android.widget.LinearLayout")
                i=0;
                for first_linear_layout in child_elements:
                    #print('first_linear_layout==',first_linear_layout)
                    if(i==5):
                        first_linear_layout.click()
                        time.sleep(2)
                        first_linear_layout.click()
                    i+=1

        time.sleep(1)
        d.press("back")
        d.press("back")
        d.press("back")
        d.press("back")

    def clear(self,d):
        device=self.device
        subprocess.Popen("adb -s "+device+ " shell am start -a android.settings.APPLICATION_DETAILS_SETTINGS -d package:com.zhixuan.ancientpoetry").stdout

        am_storage_view=self.isexists(d,['com.miui.securitycenter:id/am_storage_view'],2)

        if(am_storage_view):
            am_storage_view.click()

        action_menu_item_child_icon=self.isexists(d,['com.miui.securitycenter:id/action_menu_item_child_icon'],2)

        if(action_menu_item_child_icon):
            action_menu_item_child_icon.click()

        select_dialog_listview=self.isexists(d,['com.miui.securitycenter:id/select_dialog_listview'],2)

        if(select_dialog_listview):
            # 找到指定类型的子元素列表
            child_elements = select_dialog_listview.child(className="android.widget.TextView")
            i=0
            for first_linear_layout in child_elements:
                print(i,'first_linear_layout==',first_linear_layout)
                if(i==0):
                    first_linear_layout.click()
                    button1=self.isexists(d,['android:id/button1'],2)
                    if(button1):
                        button1.click()
                i+=1

        time.sleep(1)
        d.press("back")
        d.press("back")
        d.press("back")
        d.press("back")
        d.press("back")
        d.press("back")

        #subprocess.Popen("adb -s "+device+ " shell am start -a android.settings.APPLICATION_DETAILS_SETTINGS -d package:com.fvcorp.android.aijiasuclient").stdout
        '''
        settings=self.isexists(d,['com.android.settings:id/list'],2)

        if(settings):
            # 找到指定类型的子元素列表
            child_elements = settings.child(className="android.widget.LinearLayout")
            i=0;
            for first_linear_layout in child_elements:
                print(i,'first_linear_layout==',first_linear_layout)
                if(i==6):
                    try:
                        first_linear_layout.click()
                        button1_negative=self.isexists(d,['com.android.settings:id/button1_negative'],2)
                        if(button1_negative):
                            button1_negative.click()
                        button2=self.isexists(d,['android:id/button2'],2)
                        if(button2):
                            button2.click()
                        button1=self.isexists(d,['android:id/button1'],2)
                        if(button1):
                            button1.click()
                    except Exception as e:
                        print("thread_function thred except ............",e)
                i+=1
        '''


    def randclick(self,d,element):
        try:
            bounds = element.info['bounds']
            # 输出坐标信息
            print("元素左上角坐标 (x, y):", bounds['left'], bounds['top'])
            print("元素右下角坐标 (x, y):", bounds['right'], bounds['bottom'])
            x=random.randint(bounds['left'], bounds['right'])
            y=random.randint(bounds['top'], bounds['bottom'])
            print("元素坐标 (x, y):", x, y)
            d.click(x,y)
        except Exception as e:
            print("randclick except ............",e)


    @func_set_timeout(500)
    def do(self):
        device=self.device
        i=self.si
        change=self.schange

        #appName='com.example.myapplication'
        appName='com.zhixuan.ancientpoetry'

        subprocess.Popen("adb -s "+device+ " shell am force-stop "+appName).stdout

        '''
        subprocess.Popen("adb -s "+device+ " shell  su").stdout
        subprocess.Popen("adb -s "+device+ " shell  rm -rf /data/user/0/"+appName+"/*").stdout
        subprocess.Popen("adb -s "+device+ " shell  su").stdout
        subprocess.Popen("adb -s "+device+ " shell  rm -rf /data/data/"+appName+"/*").stdout
        '''

        #res=self.api.sets5(self.Names,'183.56.249.229','16817','1710939513','ecefy5b0')
        #print('s5=',res)


        #change.oaid(device)


        model=subprocess.Popen("adb -s "+device+ " shell getprop ro.product.model",shell=True, stdout=subprocess.PIPE).stdout.read()
        print('model========',model)
        resolution=subprocess.Popen("adb -s "+device+ " shell wm size",shell=True, stdout=subprocess.PIPE).stdout.read()
        print('resolution========',resolution)
        #change.sqlinsertInfo(str(my_defs[i].num)+'-'+str(d),'',model['msg'],resolution['msg'])


        r=subprocess.Popen("adb -s "+device+" shell pm list packages ",shell=True, stdout=subprocess.PIPE).stdout.read()
        b=True
        text=r.decode('utf-8')
        #print('text========',text)
        if(appName not in text):
            b=False
            print('app not install')
            print(subprocess.Popen("adb -s "+device+ " install jsgs.apk",shell=True, stdout=subprocess.PIPE).stdout.read())
            #self.api.runApk(self.Names,'com.innke.zhanshang')
        if(b):
            d = u2.connect(device)
            self.flight(d)
            self.clear(d)

            subprocess.Popen("adb -s "+device+ " shell am start com.zhixuan.ancientpoetry/.ui.SplashActivity",shell=True, stdout=subprocess.PIPE).stdout.read()

            try:
                if(d(resourceId='com.android.browser:id/main_content').exists):
                    print(device)
            except:
                print("except ............")
                print("adb -s "+device+ " shell /data/local/tmp/atx-agent server -d --stop")

                try:
                    # 执行系统命令并获取输出结果
                    print(subprocess.Popen("adb -s "+device+ " shell /data/local/tmp/atx-agent server -d --stop",shell=True, stdout=subprocess.PIPE).stdout.read())
                except subprocess.CalledProcessError as e:
                    # 处理子进程执行过程中的异常
                    print("adb子进程执行出现异常:", e)
                    # 继续执行下一步逻辑
                finally:
                    time.sleep(3)
                    print('finally replace')

            btn_main=self.isexists(d,['com.zhixuan.ancientpoetry:id/btn_main'],2)
            if(btn_main):
                self.randclick(d,btn_main)

            cb_agree=self.isexists(d,['com.zhixuan.ancientpoetry:id/cb_agree'],2)
            if(cb_agree):
                self.randclick(d,cb_agree)

            img_login=self.isexists(d,['com.zhixuan.ancientpoetry:id/img_login'],2)
            if(img_login):
                print('img_login')
                time.sleep(0.2)
                self.randclick(d,img_login)
            else:
                print('img_login is not exist')

            permission_allow_button=self.isexists(d,['com.android.packageinstaller:id/permission_allow_button','com.lbe.security.miui:id/permission_allow_foreground_only_button'],1)
            if(permission_allow_button):
                self.randclick(d,permission_allow_button)

            permission_allow_button=self.isexists(d,['com.android.packageinstaller:id/permission_allow_button','com.lbe.security.miui:id/permission_allow_foreground_only_button'],1)
            if(permission_allow_button):
                self.randclick(d,permission_allow_button)

            for i in range(5):

                x,y,label=yoloimg.imagecv(d)
                if(label is not None):
                    print('label===',label)
                    d.click(x,y)
                else:
                    random_int = random.randint(1, 100000)
                    screenshot = d.screenshot(format='opencv')
                    tvNext=self.isexists(d,['com.zhixuan.ancientpoetry:id/tvNext'],1)
                    btn_main=self.isexists(d,['com.zhixuan.ancientpoetry:id/btn_main'],1)
                    if(not tvNext and not btn_main):
                        cv2.imwrite('E:\\image5\\713-'+str(random_int)+'.png', screenshot, [int(cv2.IMWRITE_PNG_COMPRESSION), 0])

                tvNext=self.isexists(d,['com.zhixuan.ancientpoetry:id/tvNext'],1)
                if(tvNext):
                    print("tvNext is exist")
                    time.sleep(0.1)
                    self.randclick(d,tvNext)

                permission_allow_button=self.isexists(d,['com.android.packageinstaller:id/permission_allow_button','com.lbe.security.miui:id/permission_allow_foreground_only_button'],1)
                if(permission_allow_button):
                    permission_allow_button.click()

                permission_allow_button=self.isexists(d,['com.android.packageinstaller:id/permission_allow_button','com.lbe.security.miui:id/permission_allow_foreground_only_button'],1)
                if(permission_allow_button):
                    permission_allow_button.click()

                time.sleep(0.2)

        subprocess.Popen("adb -s "+device+ " shell am force-stop "+appName).stdout

        return 1





